package com.seata.simples.common.interceptor;

import io.seata.core.context.RootContext;
import lombok.NoArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.*;
import org.springframework.http.client.support.HttpRequestWrapper;

import java.io.IOException;

/**
 * @version V1.0
 * @Author 宋聚智
 * @Date 2019/11/6 13:19
 * @description
 * @Modify By：
 * @ModifyTime： 2019/11/6
 * @Modify marker：
 **/
@NoArgsConstructor
public class SeataRestTemplateInterceptor implements ClientHttpRequestInterceptor {

    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
        HttpRequestWrapper requestWrapper= new HttpRequestWrapper(httpRequest);
        String xid= RootContext.getXID();
        if(StringUtils.isNotBlank(xid)){
            requestWrapper.getHeaders().add(RootContext.KEY_XID,xid);
        }
        return clientHttpRequestExecution.execute(requestWrapper,bytes);
    }
}
